"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.UploadWebLayout = void 0;

var _react = _interopRequireWildcard(require("react"));

var _configContext = require("../../../extends/configContext");

var _classnames = _interopRequireDefault(require("classnames"));

var _uuid = require("../../../utils/uuid");

var _utils = require("../utils");

var _icon = _interopRequireDefault(require("../../icon"));

var _imagePreviewer = _interopRequireDefault(require("../../image-previewer"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

/**
 * 拖拽
 */
function Dragger(props) {
  var children = props.children,
      onFile = props.onFile;

  var onDrop = function onDrop(e) {
    e.preventDefault();
    typeof onFile === 'function' && onFile(e.dataTransfer.files);
  };

  var handleDragover = function handleDragover(e) {
    e.preventDefault();
  };

  var handleDragleave = function handleDragleave(e) {
    e.preventDefault();
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: "dragger",
    onDrop: onDrop,
    onDragOver: handleDragover,
    onDragLeave: handleDragleave
  }, children);
}

var getAttachIcon = function getAttachIcon(fileType) {
  var _fileType$toString;

  var type = (fileType === null || fileType === void 0 ? void 0 : (_fileType$toString = fileType.toString()) === null || _fileType$toString === void 0 ? void 0 : _fileType$toString.toUpperCase().split('/')[1]) || '';
  type = type.substr(type.lastIndexOf('.') + 1);
  var iconType = '';

  switch (type) {
    case 'XLS':
    case 'XLSX':
    case 'SHEET':
      iconType = 'xls-outlined.86ffbb304f441a3ac39d0a2b6559d119a876b992.png';
      break;

    case 'DOC':
    case 'DOCX':
    case 'DOCUMENT':
      iconType = 'doc-outlined.2c3f996d6c8e141beea3a4dd2e4f92e72927241c.png';
      break;

    case 'PPT':
    case 'PPTX':
    case 'PRESENTATION':
      iconType = 'ppt-outlined.c633840874bf2f06dd0dddc96f19f2698619e51e.png';
      break;

    case 'RAR':
    case 'ZIP':
    case 'X-ZIP-COMPRESSED':
      iconType = 'zip-outlined.8c5d95e8746ea9a5b940a03e8f83d5b1ddba0211.png';
      break;

    case 'PDF':
      iconType = 'pdf-outlined.e06cb6e0559e2f2abebaa07a54ff3b34b05a4165.png';
      break;

    case 'TXT':
    case 'PLAIN':
      iconType = 'text-outlined.3422bac383a7d71bba912db8b3912471ec2869f6.png';
      break;

    case 'MP4':
      iconType = 'video-outlined.75403451dd41be304dfcbefd530ec1d560f978f4.png';
      break;

    case 'M4A':
    case 'MP3':
    case 'MPEG':
      iconType = 'audio-outlined.d04f8b9380204fe1b1b671f59145695f56cc222d.png';
      break;

    case 'PNG':
    case 'JPEG':
      iconType = 'image-outlined.8aa1c2bd1fb9a0645e09136670cfb4020aa30be3.png';
      break;

    case 'FORM':
      iconType = 'form-outlined.7edcdca23038bdd7f2b72f2b897388e5d8acb79f.png';
      break;

    default:
      iconType = 'file-outlined.8dafcd0a20ee70430ba1d3420e015a232a64fa05.png';
      break;
  }

  return "https://imgcache.qq.com/operation/dianshi/other/".concat(iconType);
};

var handleFileSize = function handleFileSize(fileSize) {
  if (!fileSize) return '';

  if (fileSize > 1024000) {
    return "".concat((fileSize / 1024000).toFixed(2), " MB");
  }

  if (fileSize > 1024) {
    return "".concat((fileSize / 1024).toFixed(2), " KB");
  }

  return "".concat(fileSize, " B");
};
/**
 * 上传进度样式
 * @param props file文件
 */


function DefaultProgressRender(props) {
  var file = props.file,
      listType = props.listType;

  var _useContext = (0, _react.useContext)(_configContext.ConfigContext),
      clsPrefix = _useContext.clsPrefix;

  var componentClassName = (0, _classnames.default)("".concat(clsPrefix, "-upload-list-").concat(listType));

  var _useState = (0, _react.useState)(file.percent || 0),
      _useState2 = _slicedToArray(_useState, 2),
      percent = _useState2[0],
      setPercent = _useState2[1];

  (0, _react.useEffect)(function () {
    setTimeout(function () {
      setPercent(file.percent || 0);
    }, 0);
  }, [file.percent]);
  return /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(componentClassName, "-process")
  }, /*#__PURE__*/_react.default.createElement(_icon.default, {
    className: "".concat(componentClassName, "-process__icon"),
    name: "LoadingOutlined",
    size: 20
  }), percent > 0 && /*#__PURE__*/_react.default.createElement("span", {
    className: "".concat(componentClassName, "-process__text")
  }, percent, "%"));
}
/**
 * 上传文件展示列表
 */


function UploadFileList(props) {
  var listType = props.listType,
      _props$fileList = props.fileList,
      fileList = _props$fileList === void 0 ? [] : _props$fileList,
      onRemove = props.onRemove,
      onPreview = props.onPreview,
      progressRender = props.progressRender;

  var _useContext2 = (0, _react.useContext)(_configContext.ConfigContext),
      clsPrefix = _useContext2.clsPrefix;

  var componentClassName = (0, _classnames.default)("".concat(clsPrefix, "-upload-list-").concat(listType)); // 图片预览

  var _React$useState = _react.default.useState(false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      visible = _React$useState2[0],
      setVisible = _React$useState2[1];

  var _React$useState3 = _react.default.useState(null),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      defaultImg = _React$useState4[0],
      setDefaultImg = _React$useState4[1];

  var _React$useState5 = _react.default.useState([]),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      imgUrls = _React$useState6[0],
      setImgUrls = _React$useState6[1];

  var ImagePreviewerRef = _react.default.useRef(null); // 预览图片组


  (0, _react.useEffect)(function () {
    setImgUrls(fileList.filter(function (file) {
      return (0, _utils.isImageFileType)(file === null || file === void 0 ? void 0 : file.type) && (file.url || file.thumbUrl);
    }).map(function (file) {
      return file.url || file.thumbUrl;
    }));
  }, [fileList.length]); // 删除文件

  var onRemoveFile = function onRemoveFile(file) {
    onRemove(file);
  }; // 预览文件


  var onPreviewFile = function onPreviewFile(file, index) {
    onPreview(file); // 预览图片

    if ((0, _utils.isImageFileType)(file === null || file === void 0 ? void 0 : file.type) && (file.url || file.thumbUrl)) {
      setDefaultImg(imgUrls[index]);
      setTimeout(function () {
        ImagePreviewerRef.current.show();
      }, 0);
    }
  };

  var listElement = fileList.map(function (file, index) {
    return /*#__PURE__*/_react.default.createElement("div", {
      key: file.uid,
      className: (0, _classnames.default)("".concat(componentClassName, "__item"), {
        'is-error': file.status === 'error',
        'is-success': file.status === 'success'
      })
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(componentClassName, "__info"),
      onClick: function onClick() {
        return onPreviewFile(file, index);
      }
    }, (0, _utils.isImageFileType)(file.type) && file.thumbUrl ? /*#__PURE__*/_react.default.createElement("img", {
      src: file.thumbUrl,
      alt: file.name,
      className: "".concat(componentClassName, "__thumbUrl")
    }) : /*#__PURE__*/_react.default.createElement("img", {
      src: getAttachIcon(file === null || file === void 0 ? void 0 : file.type),
      className: "".concat(componentClassName, "__icon"),
      alt: file.name
    }), /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(componentClassName, "__name")
    }, file.name), /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(componentClassName, "__filesize")
    }, handleFileSize(file.size || (file === null || file === void 0 ? void 0 : file.fileSize)))), /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(componentClassName, "__operate"),
      onClick: function onClick() {
        return onRemoveFile(file);
      }
    }, /*#__PURE__*/_react.default.createElement(_icon.default, {
      name: "DeleteOutlined"
    })), file.status === 'uploading' && (typeof progressRender === 'function' ? /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(componentClassName, "__process")
    }, progressRender(file)) : /*#__PURE__*/_react.default.createElement(DefaultProgressRender, {
      listType: listType,
      file: file
    })));
  }); // 卡片模式

  if (listType === 'card') {
    listElement = fileList.map(function (file, index) {
      return /*#__PURE__*/_react.default.createElement("div", {
        key: file.uid,
        className: (0, _classnames.default)("".concat(componentClassName, "__item"), {
          'is-error': file.status === 'error'
        })
      }, (0, _utils.isImageFileType)(file.type) && file.thumbUrl ? /*#__PURE__*/_react.default.createElement("img", {
        src: file.thumbUrl,
        alt: file.name,
        className: "".concat(componentClassName, "__thumbUrl"),
        onClick: function onClick() {
          return onPreviewFile(file, index);
        }
      }) : /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(componentClassName, "__info"),
        onClick: function onClick() {
          return onPreviewFile(file, index);
        }
      }, /*#__PURE__*/_react.default.createElement("img", {
        src: getAttachIcon(file === null || file === void 0 ? void 0 : file.type),
        className: "".concat(componentClassName, "__thumbUrl"),
        alt: file.name
      }), /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(componentClassName, "__name")
      }, file.name, " ", file.status, " ", file.percent)), file.status === 'uploading' ? typeof progressRender === 'function' ? progressRender(file) : /*#__PURE__*/_react.default.createElement(DefaultProgressRender, {
        listType: listType,
        file: file
      }) : /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(componentClassName, "__operate"),
        onClick: function onClick() {
          return onRemoveFile(file);
        }
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        name: "DeleteOutlined"
      })));
    });
  }

  return /*#__PURE__*/_react.default.createElement("div", {
    className: componentClassName
  }, listElement, props.children, /*#__PURE__*/_react.default.createElement(_imagePreviewer.default, {
    visible: visible,
    ref: ImagePreviewerRef,
    onClose: function onClose() {
      setVisible(false);
    },
    imgUrls: imgUrls,
    currentUrl: defaultImg
  }));
}
/**
 * 文件上传组件
 * TODO: 通过ref抛出一些方法
 */


var UploadWebLayout = function UploadWebLayout(props, ref) {
  var className = props.className,
      style = props.style,
      listType = props.listType,
      fileList = props.fileList,
      children = props.children,
      multiple = props.multiple,
      accept = props.accept,
      limit = props.limit,
      progressRender = props.progressRender,
      onChange = props.onChange,
      onPreview = props.onPreview,
      beforeUpload = props.beforeUpload,
      customRequest = props.customRequest,
      wxChooseImage = props.wxChooseImage;

  var _useContext3 = (0, _react.useContext)(_configContext.ConfigContext),
      clsPrefix = _useContext3.clsPrefix;

  fileList.forEach(function (file, index) {
    var _file$uid;

    file.uid = (_file$uid = file.uid) !== null && _file$uid !== void 0 ? _file$uid : "".concat(index, "__").concat((0, _uuid.uuid)());
  });
  var inputRef = (0, _react.useRef)(null);
  var componentClassName = "".concat(clsPrefix, "-upload");
  var uploadClassName = (0, _classnames.default)(className, componentClassName, {
    'is-card': listType === 'card'
  });

  var _useState3 = (0, _react.useState)(fileList),
      _useState4 = _slicedToArray(_useState3, 2),
      showFileList = _useState4[0],
      setShowFileList = _useState4[1];

  var onInternalChange = function onInternalChange() {
    // Cut to match count
    if (limit) {
      showFileList.splice(limit);
    }

    showFileList.forEach(function (file) {
      try {
        file.thumbUrl = URL.createObjectURL(file.originFileObj);
      } catch (err) {
        return;
      }
    });
    setShowFileList(showFileList);
    typeof onChange === 'function' && onChange(showFileList);
  }; // 上传文件


  var uploadFiles = /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(files) {
      var cloneList, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              cloneList = _toConsumableArray(files);
              cloneList = cloneList.map(function (file, index) {
                var _file$uid2;

                file.uid = (_file$uid2 = file.uid) !== null && _file$uid2 !== void 0 ? _file$uid2 : "".concat(index, "__").concat((0, _uuid.uuid)());
                return (0, _utils.fileToObject)(file);
              });

              if (!(typeof beforeUpload === 'function')) {
                _context.next = 8;
                break;
              }

              _context.next = 5;
              return beforeUpload(cloneList, showFileList);

            case 5:
              res = _context.sent;

              if (res) {
                _context.next = 8;
                break;
              }

              return _context.abrupt("return");

            case 8:
              showFileList.push.apply(showFileList, _toConsumableArray(cloneList));
              onInternalChange(showFileList);

              if (limit) {
                cloneList = cloneList.slice(0, limit);
              }

              postFiles(cloneList);

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function uploadFiles(_x) {
      return _ref.apply(this, arguments);
    };
  }(); // 发送文件


  var postFiles = function postFiles(files) {
    files.forEach(function (file) {
      if (typeof customRequest === 'function') {
        // 自定义上传钩子
        customRequest(file, showFileList, onInternalChange).then(function (res) {
          if (!res) {
            file.status = 'error';
            return;
          }

          file.status = 'success';
        }).catch(function (err) {
          file.status = 'error';
        }).finally(function () {
          onInternalChange(showFileList);
        });
      }
    });
  }; // 删除文件


  var removeFile = function removeFile(deleteFile) {
    showFileList.splice(showFileList.findIndex(function (file) {
      return file.uid === deleteFile.uid;
    }), 1);
    onInternalChange(showFileList);
  }; // 查看文件


  var previewFile = function previewFile(file) {
    typeof onPreview === 'function' && onPreview(file);
  }; // input change事件


  var handleChange = function handleChange(e, wxFiles) {
    if (wxFiles) {
      uploadFiles(wxFiles);
      return;
    }

    if (e.target instanceof HTMLInputElement) {
      var files = e.target.files;

      if (!files) {
        return;
      }

      uploadFiles(files);
      inputRef.current.value = null;
    }
  }; // 触发input事件


  var trggerInput = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(e) {
      var files;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(e.target.id === 'trgger-file-choose-input')) {
                _context2.next = 2;
                break;
              }

              return _context2.abrupt("return");

            case 2:
              if (!(typeof wxChooseImage === 'function')) {
                _context2.next = 9;
                break;
              }

              _context2.next = 5;
              return wxChooseImage();

            case 5:
              files = _context2.sent;

              if (files && files instanceof Array && files.length) {
                handleChange('', files);
              } else {
                inputRef.current.click();
              }

              _context2.next = 10;
              break;

            case 9:
              inputRef.current.click();

            case 10:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function trggerInput(_x2) {
      return _ref2.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/_react.default.createElement("div", {
    className: uploadClassName,
    style: style
  }, /*#__PURE__*/_react.default.createElement(UploadFileList, {
    onRemove: removeFile,
    onPreview: previewFile,
    listType: listType,
    fileList: showFileList,
    progressRender: progressRender
  }, limit && (showFileList === null || showFileList === void 0 ? void 0 : showFileList.length) >= limit ? '' : /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(componentClassName, "__area"),
    onClick: trggerInput
  }, /*#__PURE__*/_react.default.createElement(Dragger, {
    onFile: uploadFiles
  }, children), /*#__PURE__*/_react.default.createElement("input", {
    id: "trgger-file-choose-input",
    className: "".concat(componentClassName, "__input"),
    type: "file",
    ref: inputRef,
    onChange: handleChange,
    multiple: multiple,
    accept: accept
  }))));
};

exports.UploadWebLayout = UploadWebLayout;
UploadWebLayout.defaultProps = {
  listType: 'list',
  fileList: []
};